<?php
/**
 * Created by PhpStorm.
 * User: work
 * Date: 18-6-23
 * Time: 下午4:57
 */

namespace PddWechat\Models\User\Dao;


use Dai\Framework\Base\BaseDao;
use Dai\Framework\Library\Log;
use PddWechat\Models\User\DataObject\UserDo;

/**
 * Class UserDao
 * @dataObject(\PddWechat\Models\User\DataObject\UserDo)
 * @package PddWechat\Models\User\Dao
 */
class UserDao extends BaseDao
{

    /**
     * @param UserDo $userDo
     * @return UserDo
     */
    public function insert( UserDo $userDo )
    {
        $userDo->id =  $this->execute("user.user.insert", $userDo);
        return $userDo;
    }


    /**
     * @param $uid
     * @return object
     */
    public function select( $uid )
    {
        $param = [
            'select' => '*',
            'where' => " id = $uid",
        ];
        $res = $this->execute("user.user.select", $param);
        if( count($res) > 0 ){
            return $this->trimBase($res[0]);
        }else {
            return (Object)[];
        }
    }

    /**
     * @param $uids
     * @return array
     */
    public function selectByUids( $uids )
    {
        if( count($uids) === 0) {
            return [];
        }

        $param = [
            'where' => " id in (".implode(",", $uids).")",
            'select' => '*',
        ];
        $res = $this->execute("user.user.select", $param);
        $ret = [];
        if( count($res) > 0 ){
            foreach ($res as $re) {
                $ret[$re['id']] = $this->trimBase($re);
            }
        }
        return $ret;
    }

    public function total(){
        $param = [
            'select' => 'count(1) AS cnt ',
        ];

        $res = $this->execute("user.user.select", $param);
        return intval($res[0]['cnt']);
    }

    public function selectList($pn, $rn){
        $param = [
            'orderBy' => " id desc LIMIT $pn, $rn",
            'select' => '*',
        ];

        $res = $this->execute("user.user.select", $param);
        $output = [];
        if( count($res) > 0 ) {
            foreach ($res as $item) {
                $output[] = $this->trimBase($item);
            }
        }
        return $output;
    }

    public function totalList(){
        $res = $this->execute("user.user.total_list", []);
        return intval($res[0]['cnt']);
    }

    /**
     * @param $uids
     * @return array
     */
    public function selects($uids)
    {
        if(count($uids) == 0){
            return [];
        }

        $param = [
            'uids' => implode("," , $uids),
            'select' => '*',
        ];
        $res = $this->execute("user.user.select_s", $param);
        $output = [];
        if( count($res) > 0 ) {
            foreach ($res as $item) {
                $output[] = $this->trimBase($item);
            }
        }
        return $output;
    }

    /**
     * @param $openId
     * @return null|UserDo
     */
    public function selectByOpenId($openId)
    {
        $param = [
            'openId' => $openId,
            'select' => '*',
        ];
        $res = $this->execute("user.user.select_by_open_id", $param);
        if( count($res) > 0 ) {
            /** @var UserDo $ret */
            $ret = $this->trimBase($res[0]);
            return $ret;
        }
        return null;
    }


    /**
     * @param $inviteCode
     * @return null|UserDo
     */
    public function selectByInviteCode($inviteCode)
    {
        $param = [
            'inviteCode' => $inviteCode,
            'select' => '*',
        ];
        $res = $this->execute("user.user.select_by_invite_code", $param);
        if( count($res) > 0 ) {
            /** @var UserDo $ret */
            $ret = $this->trimBase($res[0]);
            return $ret;
        }
        return null;
    }

    /**
     * @param $openIds
     * @return array
     */
    public function selectByOpenIds($openIds) {
        if( count($openIds) == 0) {
            return [];
        }

        $openIdNews = [];
        foreach ($openIds as $openId) {
            $openIdNews[] = "'$openId'";
        }

        $sql = "SELECT * FROM jd.user WHERE openId in (".   implode(",", $openIdNews).") ORDER BY id DESC";
        $res = $this->queryRaw($sql);
        $ret = [];

        if( count($res) > 0 ) {
            foreach ($res as $t ) {
                /** @var UserDo $t */
                unset($t['password']);
                unset($t['salt']);
                $ret[$t['openId']] = $this->trimBase($t);
            }
        }
        var_dump( $ret);
        return $ret;
    }

    public function getUsersBuUids($uids) {
        if( count($uids) == 0) {
            return [];
        }
        $uidNews = [];
        foreach ($uids as $uid) {
            $uidNews[] = "'$uid'";
        }
        $sql = "SELECT id,userName,avatar FROM jd.user WHERE id in (".   implode(",", $uidNews).") ORDER BY id DESC";
        $res = $this->queryRaw($sql);
        $output = [];
        if( count($res) > 0 ) {
            foreach ($res as $item) {
                $output[] = $this->trimBase($item);
            }
        }
        return $output;
    }

    /**
     * @param $uid
     * @return mixed
     */
    public function delete( $uid )
    {
        return $this->execute("user.user.delete", ['uid' => $uid]);
    }

    /**
     * @param UserDo $userDo
     * @param null $where
     * @return mixed
     */
    public function edit( \PddWechat\Models\User\DataObject\UserDo $userDo, $where=null){
        if( trim($where) == "" && intval($userDo->id) <= 0) {
            Log::error("update where or id must exist");
            return false;
        }
        $userDo->updateTime =  date('Y-m-d H:i:s', time());
        $param = [
            'update' =>  json_decode(json_encode($userDo), true),
            'where' => (trim($where) == "") ? ' id = '. $userDo->id : $where,
        ];
        Log::info("edit user ,param is ".var_export($param, true));
        return $this->execute("user.user.edit", $param);
    }

    public function getDirectMemberNumByOpenId( $inviteopenid ) {
        $param = [
            'inviteOpenId' => $inviteopenid,
            'select' => "count(*) as cnt"
        ];
        $res = $this->execute("user.user.select_direct_member",$param);
        return $res[0]['cnt'];
    }

    public function getMemberListByOpenId($openId,$select = "*") {
        $param = [
            'inviteOpenId' => $openId,
            'select' => $select,
        ];
        $res = $this->execute("user.user.select_direct_member",$param);
        if( count($res) > 0 ) {
            return $res;
        }
        return null;
    }

    public function getIndirectMemberNumByOpenId($openIds) {
        if( count($openIds) == 0) {
            return [];
        }
        $openIdNews = [];
        foreach ($openIds as $openId) {
            $openIdNews[] = "'$openId'";
        }
        $sql = "SELECT count(*) as cnt FROM jd.user WHERE inviteOpenId in (".   implode(",", $openIdNews).") ORDER BY id DESC";
        $res = $this->queryRaw($sql);
        return $res[0]['cnt'];
    }

    public function getMemberListAsPageListByOpenId($openId,$pn = 0,$rn = 0)
    {
        if(empty($openId)) {
            return [];
        }
        $sql = "SELECT * FROM jd.user WHERE inviteOpenId='" . $openId."' ORDER BY id DESC LIMIT ".($pn-1) * $rn . "," . $rn;
        $res = $this->queryRaw($sql);
        $output = [];
        if( count($res) > 0 ) {
            foreach ($res as $item) {
                $output[] = $this->trimBase($item);
            }
        }
        return $output;
    }

    public function getDirectMemsIndirectMemsNumByOpenIds($openIds) {
        if( count($openIds) == 0) {
            return [];
        }
        $openIdNews = [];
        foreach ($openIds as $openId) {
            $openIdNews[] = "'$openId'";
        }
        $sql = "SELECT count(*) as cnt,inviteOpenId FROM jd.user WHERE inviteOpenId IN (" . implode(",", $openIdNews).") GROUP BY inviteOpenId";
        $res = $this->queryRaw($sql);
        if(count($res) > 0) {
            return $res;
        }
        return [];
    }

    public function getDirectMemberNumByUidAndCreateTime($uid,$beginTime,$endTime) {
        if(empty($uid)) {
            return 0;
        }
        $sql = "SELECT COUNT(*) as cnt FROM jd.user WHERE inviteUid = " . intval($uid) . " AND createTime 
        BETWEEN '" . $beginTime . "' AND '" . $endTime. "'";
        $res = $this->queryRaw($sql);
        if(count($res) > 0) {
            return $res[0]['cnt'];
        }
        return 0;
    }

    public function getDirectUsersByInviteUid($uid) {
        $param = [
            'inviteUid' => $uid,
            'select' => "openId,userName",
        ];
        $res = $this->execute("user.user.select_by_invateUid", $param);
        if(count($res) > 0) {
            return $res;
        }
        return $res;
    }

    public function getIndirectUsersByInviteOpenId($openIds,$beginTime,$endTime) {
        if(count($openIds) == 0) {
            return 0;
        }
        $openIdNews = [];
        foreach ($openIds as $openId) {
            $openIdNews[] = "'$openId'";
        }
        $sql = "SELECT COUNT(*) as cnt FROM jd.user WHERE inviteOpenId in (". implode(",", $openIdNews).") AND 
        createTime BETWEEN '" . $beginTime . "' AND '" . $endTime. "'";
        $res = $this->queryRaw($sql);
        if(count($res) > 0) {
            return $res[0]['cnt'];
        }
        return 0;
    }

    public function updateUserMoneyById($uid,$money) {
        if(empty($uid)) {
            return 0;
        }
        $sql = "UPDATE jd.user SET userMoney = userMoney + " . floatval($money) . " WHERE id = " . intval($uid);
        $res = $this->execRaw($sql);
        return $res;
    }

    public function updateUserWithDrawMoney($uid,$money) {
        if(empty($uid)) {
            return 0;
        }
        $sql = "UPDATE jd.user SET userMoney = " . floatval($money) . " WHERE id = " . intval($uid);
        $res = $this->execRaw($sql);
        return $res;
    }
}